import { createTextVNode as _createTextVNode, mergeProps as _mergeProps, createVNode as _createVNode } from "vue";
import { ref, watch, provide, computed, nextTick, reactive, onMounted, defineComponent } from "vue";
import { isDef, extend, addUnit, toArray, FORM_KEY, numericProp, unknownProp, resetScroll, formatNumber, preventDefault, makeStringProp, makeNumericProp, createNamespace } from "../utils/index.mjs";
import { cutString, runSyncRule, endComposing, mapInputType, isEmptyValue, startComposing, getRuleMessage, resizeTextarea, getStringLength, runRuleValidator } from "./utils.mjs";
import { cellSharedProps } from "../cell/Cell.mjs";
import { useParent, useEventListener, CUSTOM_FIELD_INJECTION_KEY } from "@vant/use";
import { useId } from "../composables/use-id.mjs";
import { useExpose } from "../composables/use-expose.mjs";
import { Icon } from "../icon/index.mjs";
import { Cell } from "../cell/index.mjs";
const [name, bem] = createNamespace("field");
const fieldSharedProps = {
  id: String,
  name: String, // 名称, 提交表单的标识符  Form中通过name找到相应的子组件
  leftIcon: String,
  rightIcon: String,
  autofocus: Boolean,
  clearable: Boolean,
  maxlength: numericProp, // [Number, String]
  formatter: Function,
  clearIcon: makeStringProp("clear"),
  modelValue: makeNumericProp(""), // 自定义[Number, String]设定默认值 用于双向绑定
  inputAlign: String,
  placeholder: String,
  autocomplete: String,
  autocapitalize: String,
  autocorrect: String, // 箭头方向,可选值为 left up down
  errorMessage: String, // 底部错误提示文案, 为空时不展示 该值存在时一直显示 优先级> rules返回的值检查信息
  enterkeyhint: String,
  clearTrigger: makeStringProp("focus"), // 定义为string且设定默认值 // 清除数据的时机
  formatTrigger: makeStringProp("onChange"), // 格式化数据的时机
  spellcheck: { // 是否开启输入检查
    type: Boolean,
    default: null
  },
  error: { // 是否将输入内容标红
    type: Boolean,
    default: null
  },
  disabled: {
    type: Boolean,
    default: null
  },
  readonly: {
    type: Boolean,
    default: null
  }
};
const fieldProps = extend({}, cellSharedProps, fieldSharedProps, {
  rows: numericProp,
  type: makeStringProp("text"), // 输入框类型, 可选值为 tel digit整数 number textarea password 等
  rules: Array, // 表单校验规则
  autosize: [Boolean, Object],
  labelWidth: numericProp,
  labelClass: unknownProp,
  labelAlign: String,
  showWordLimit: Boolean,
  errorMessageAlign: String,
  colon: {
    type: Boolean,
    default: null
  }
});
var stdin_default = defineComponent({
  name,
  props: fieldProps,
  emits: ["blur", "focus", "clear", "keypress", "clickInput", "endValidate", "startValidate", "clickLeftIcon", "clickRightIcon", "update:modelValue"],
  setup(props, {
    emit,
    slots
  }) {
    const id = useId();
    const state = reactive({
      status: "unvalidated",
      focused: false,
      validateMessage: ""
    });
    const inputRef = ref();
    const clearIconRef = ref();
    const customValue = ref();
    // 结构从form穿透过来的params
    const {
      parent: form
    } = useParent(FORM_KEY);
    // field输入为string和number, 将null强制转为''
    const getModelValue = () => {
      var _a;
      return String((_a = props.modelValue) != null ? _a : "");
    };
    const getProp = (key) => {
      if (isDef(props[key])) {
        return props[key];
      }
      if (form && isDef(form.props[key])) {
        return form.props[key];
      }
    };

    const showClear = computed(() => {
      const readonly = getProp("readonly");
      if (props.clearable && !readonly) {
        const hasValue = getModelValue() !== "";
        const trigger = props.clearTrigger === "always" || props.clearTrigger === "focus" && state.focused;
        return hasValue && trigger;
      }
      return false;
    });
    // 使用input插槽时, 通过provide及inject 关联子组件, customValue.value 绑定为子组件的getter
    const formValue = computed(() => {
      if (customValue.value && slots.input) {
        return customValue.value();
      }
      return props.modelValue;
    });

    // 是否展示必填星号
    const showRequiredMark = computed(() => {
      var _a;
      const required = getProp("required");
      if (required === "auto") {
        return (_a = props.rules) == null ? void 0 : _a.some((rule) => rule.required);
      }
      return required;
    });

    // 通过reduce配合promise, 跑完rules里面配置的全部规则, 保证最后返回的为promise
    // 验证成功与失败 通过receive的state来判断
    const runRules = (rules) => rules.reduce((promise, rule) => promise.then(() => {
      if (state.status === "failed") {
        return;
      }
      let {
        value
      } = formValue;
      if (rule.formatter) {
        value = rule.formatter(value, rule);
      }
      if (!runSyncRule(value, rule)) {
        state.status = "failed";
        state.validateMessage = getRuleMessage(value, rule);
        return;
      }
      if (rule.validator) {
        // validateEmpty为空不校验时, 直接调过该项的配置
        if (isEmptyValue(value) && rule.validateEmpty === false) {
          return;
        }
        return runRuleValidator(value, rule).then((result) => {
          if (result && typeof result === "string") {
            state.status = "failed";
            state.validateMessage = result;
          } else if (result === false) {
            state.status = "failed";
            state.validateMessage = getRuleMessage(value, rule);
          }
        });
      }
    }), Promise.resolve());
    // 重置验证状态
    const resetValidation = () => {
      state.status = "unvalidated";
      state.validateMessage = "";
    };
    // 验证完毕emit相关事件
    const endValidate = () => emit("endValidate", {
      status: state.status,
      message: state.validateMessage
    });
    // 暴露给外部使用, 手动触发
    // 返回promise 失败时可以获取file的name及错误提示message
    const validate = (rules = props.rules) => new Promise((resolve) => {
      resetValidation();
      if (rules) {
        emit("startValidate");
        runRules(rules).then(() => {
          if (state.status === "failed") {
            resolve({
              name: props.name,
              message: state.validateMessage
            });
            endValidate();
          } else {
            state.status = "passed";
            resolve();
            endValidate();
          }
        });
      } else {
        resolve();
      }
    });

    //  form和rule中都会配置validateTrigger 触发方式
    // form的权重更高  当form中有配置onFoucs或onChange
    // field中的input操作时, 手动触发相应的验证
    const validateWithTrigger = (trigger) => {
      // 当在form中使用才会触发
      if (form && props.rules) {
        const {
          validateTrigger
        } = form.props;
        const defaultTrigger = toArray(validateTrigger).includes(trigger);
        // 过滤rules中rule和form中配置的项
        const rules = props.rules.filter((rule) => {
          if (rule.trigger) {
            return toArray(rule.trigger).includes(trigger);
          }
          return defaultTrigger;
        });
        // 有匹配开始验证
        if (rules.length) {
          validate(rules);
        }
      }
    };

    // textarea时限制输入长度
    // onInput触发时value和getModelValue不相同
    const limitValueLength = (value) => {
      var _a;
      const {
        maxlength
      } = props;
      if (isDef(maxlength) && getStringLength(value) > +maxlength) {
        const modelValue = getModelValue();
        // 旧值刚好等于maxlength, 新增处理也相同, 不如直接跳过 oninput时
        if (modelValue && getStringLength(modelValue) === +maxlength) {
          return modelValue;
        }
        // 当粘贴的时候要限制长度, 通过selectionEnd的位置来确定需要删除文字的位置 onInput时
        const selectionEnd = (_a = inputRef.value) == null ? void 0 : _a.selectionEnd;
        if (state.focused && selectionEnd) {
          const valueArr = [...value];
          const exceededLength = valueArr.length - +maxlength;
          valueArr.splice(selectionEnd - exceededLength, exceededLength);
          return valueArr.join("");
        }
        // 外部修改modelValue时
        return cutString(value, +maxlength);
      }
      return value;
    };

    // 使用位置 ()=> props.modelValue >>> watch(getModelValue()) onmouted(getModelValue(), props.formatTrigger) onInput onBlur(getModelValue(),'onBlur')
    // watch onmouted onBlur传入getModelValue() onInput(e.target.value)
    // 其中watch和onmouted是外部影响内部, onInput和onBlur是内部影响外部
    // trriger watch(onChage) onmouted(props.formatTrigger) onInput(onChage) onBlur(onBlur)
    // formatTrigger默认为onChage, 当props设定时会覆盖
    // updateValue 会修改双向绑定值及实际值
    const updateValue = (value, trigger = "onChange") => {
      const originalValue = value;
      value = limitValueLength(value);
      const limitDiffLen = getStringLength(originalValue) - getStringLength(value);
      if (props.type === "number" || props.type === "digit") {
        const isNumber = props.type === "number";
        value = formatNumber(value, isNumber, isNumber);
      }
      let formatterDiffLen = 0;
      // formatter当有格式化时,强制修改双向绑定值及inputRef.value的值
      // 到此value的值处理全部完毕
      if (props.formatter && trigger === props.formatTrigger) {
        const {
          formatter,
          maxlength
        } = props;
        value = formatter(value);
        if (isDef(maxlength) && getStringLength(value) > +maxlength) {
          value = cutString(value, +maxlength);
        }
        if (inputRef.value && state.focused) {
          const {
            selectionEnd
          } = inputRef.value;
          const bcoVal = cutString(originalValue, selectionEnd);
          formatterDiffLen = getStringLength(formatter(bcoVal)) - getStringLength(bcoVal);
        }
      }
      if (inputRef.value && inputRef.value.value !== value) {
        if (state.focused) {
          let {
            selectionStart,
            selectionEnd
          } = inputRef.value;
          inputRef.value.value = value;
          if (isDef(selectionStart) && isDef(selectionEnd)) {
            const valueLen = getStringLength(value);
            if (limitDiffLen) {
              selectionStart -= limitDiffLen;
              selectionEnd -= limitDiffLen;
            } else if (formatterDiffLen) {
              selectionStart += formatterDiffLen;
              selectionEnd += formatterDiffLen;
            }
            // 当设定当期复制文本位置
            inputRef.value.setSelectionRange(Math.min(selectionStart, valueLen), Math.min(selectionEnd, valueLen));
          }
        } else {
          // 手动修改input的值
          inputRef.value.value = value;
        }
      }
      if (value !== props.modelValue) {
        emit("update:modelValue", value);
      }
    };
    const onInput = (event) => {
      if (!event.target.composing) {
        updateValue(event.target.value);
      }
    };
    const blur = () => {
      var _a;
      return (_a = inputRef.value) == null ? void 0 : _a.blur();
    };
    const focus = () => {
      var _a;
      return (_a = inputRef.value) == null ? void 0 : _a.focus();
    };
    const adjustTextareaSize = () => {
      const input = inputRef.value;
      if (props.type === "textarea" && props.autosize && input) {
        resizeTextarea(input, props.autosize);
      }
    };
    const onFocus = (event) => {
      state.focused = true;
      emit("focus", event);
      nextTick(adjustTextareaSize);
      if (getProp("readonly")) {
        blur();
      }
    };
    const onBlur = (event) => {
      state.focused = false;
      updateValue(getModelValue(), "onBlur");
      emit("blur", event);
      if (getProp("readonly")) {
        return;
      }
      validateWithTrigger("onBlur");
      nextTick(adjustTextareaSize);
      resetScroll();
    };
    const onClickInput = (event) => emit("clickInput", event);
    const onClickLeftIcon = (event) => emit("clickLeftIcon", event);
    const onClickRightIcon = (event) => emit("clickRightIcon", event);
    const onClear = (event) => {
      preventDefault(event);
      emit("update:modelValue", "");
      emit("clear", event);
    };
    const showError = computed(() => {
      if (typeof props.error === "boolean") {
        return props.error;
      }
      if (form && form.props.showError && state.status === "failed") {
        return true;
      }
    });
    const labelStyle = computed(() => {
      const labelWidth = getProp("labelWidth");
      const labelAlign = getProp("labelAlign");
      if (labelWidth && labelAlign !== "top") {
        return {
          width: addUnit(labelWidth)
        };
      }
    });
    
    // 监听enter键, 在form中使用可以触发提交,作为search框时确认blur
    const onKeypress = (event) => {
      const ENTER_CODE = 13;
      if (event.keyCode === ENTER_CODE) {
        const submitOnEnter = form && form.props.submitOnEnter;
        // 在textarea中enter会换行
        if (!submitOnEnter && props.type !== "textarea") {
          preventDefault(event);
        }
        if (props.type === "search") {
          blur();
        }
      }
      emit("keypress", event);
    };
    const getInputId = () => props.id || `${id}-input`;
    const getValidationStatus = () => state.status;

    // input的rander函数
    const renderInput = () => {
      const controlClass = bem("control", [getProp("inputAlign"), {
        error: showError.value,
        custom: !!slots.input,
        "min-height": props.type === "textarea" && !props.autosize
      }]);
      // 使用自定义slots.input
      if (slots.input) {
        return _createVNode("div", {
          "class": controlClass,
          "onClick": onClickInput
        }, [slots.input()]);
      }
      const inputAttrs = {
        id: getInputId(),
        ref: inputRef,
        name: props.name,
        rows: props.rows !== void 0 ? +props.rows : void 0,
        class: controlClass,
        disabled: getProp("disabled"),
        readonly: getProp("readonly"),
        autofocus: props.autofocus,
        placeholder: props.placeholder,
        autocomplete: props.autocomplete,
        autocapitalize: props.autocapitalize,
        autocorrect: props.autocorrect,
        enterkeyhint: props.enterkeyhint,
        spellcheck: props.spellcheck,
        "aria-labelledby": props.label ? `${id}-label` : void 0,
        onBlur,
        onFocus,
        onInput,
        onClick: onClickInput,
        onChange: endComposing,
        onKeypress,
        onCompositionend: endComposing,
        onCompositionstart: startComposing
      };
      if (props.type === "textarea") {
        return _createVNode("textarea", inputAttrs, null);
      }
      return _createVNode("input", _mergeProps(mapInputType(props.type), inputAttrs), null);
    };

    // 左侧图标render函数 
    const renderLeftIcon = () => {
      const leftIconSlot = slots["left-icon"];
      if (props.leftIcon || leftIconSlot) {
        return _createVNode("div", {
          "class": bem("left-icon"),
          "onClick": onClickLeftIcon
        }, [leftIconSlot ? leftIconSlot() : _createVNode(Icon, {
          "name": props.leftIcon,
          "classPrefix": props.iconPrefix
        }, null)]);
      }
    };

    // 右侧图标render函数
    const renderRightIcon = () => {
      const rightIconSlot = slots["right-icon"];
      if (props.rightIcon || rightIconSlot) {
        return _createVNode("div", {
          "class": bem("right-icon"),
          "onClick": onClickRightIcon
        }, [rightIconSlot ? rightIconSlot() : _createVNode(Icon, {
          "name": props.rightIcon,
          "classPrefix": props.iconPrefix
        }, null)]);
      }
    };

    // type='textarea' 展示的输入字符限制
    const renderWordLimit = () => {
      if (props.showWordLimit && props.maxlength) {
        const count = getStringLength(getModelValue());
        return _createVNode("div", {
          "class": bem("word-limit")
        }, [_createVNode("span", {
          "class": bem("word-num")
        }, [count]), _createTextVNode("/"), props.maxlength]);
      }
    };

    // 底部的错误提示
    const renderMessage = () => {
      // form的proos.showErrorMessage全局控制
      if (form && form.props.showErrorMessage === false) {
        return;
      }
      const message = props.errorMessage || state.validateMessage;
      if (message) {
        const slot = slots["error-message"];
        const errorMessageAlign = getProp("errorMessageAlign");
        return _createVNode("div", {
          "class": bem("error-message", errorMessageAlign)
        }, [slot ? slot({
          message
        }) : message]);
      }
    };

    // Cell组件中left列下面一行
    const renderLabel = () => {
      const labelWidth = getProp("labelWidth");
      const labelAlign = getProp("labelAlign");
      const colon = getProp("colon") ? ":" : "";
      if (slots.label) {
        return [slots.label(), colon];
      }
      if (props.label) {
        return _createVNode("label", {
          "id": `${id}-label`,
          "for": slots.input ? void 0 : getInputId(),
          "onClick": (event) => {
            preventDefault(event);
            focus();
          },
          "style": labelAlign === "top" && labelWidth ? {
            width: addUnit(labelWidth)
          } : void 0
        }, [props.label + colon]);
      }
    };

    // 将Cell组件中的right列改造为 input输入框
    const renderFieldBody = () => [_createVNode("div", {
      "class": bem("body")
    }, [renderInput(), showClear.value && _createVNode(Icon, {
      "ref": clearIconRef,
      "name": props.clearIcon,
      "class": bem("clear")
    }, null), renderRightIcon(), slots.button && _createVNode("div", {
      "class": bem("button")
    }, [slots.button()])]), renderWordLimit(), renderMessage()];

    // 向外暴露的方法  向组件实例proxy中插入一个方法
    useExpose({
      blur,
      focus,
      validate,
      formValue, // 将值返回给form中使用
      resetValidation,
      getValidationStatus
    });

    // 为field中插槽各项provide 绑定值, 及还原及触发验证各方法
    provide(CUSTOM_FIELD_INJECTION_KEY, {
      customValue,
      resetValidation,
      validateWithTrigger
    });
    watch(() => props.modelValue, () => {
      updateValue(getModelValue());
      resetValidation();
      validateWithTrigger("onChange");
      nextTick(adjustTextareaSize);
    });
    onMounted(() => {
      updateValue(getModelValue(), props.formatTrigger);
      nextTick(adjustTextareaSize);
    });
    useEventListener("touchstart", onClear, {
      target: computed(() => {
        var _a;
        return (_a = clearIconRef.value) == null ? void 0 : _a.$el;
      })
    });


    return () => {
      const disabled = getProp("disabled");
      const labelAlign = getProp("labelAlign");
      const LeftIcon = renderLeftIcon();
      const renderTitle = () => {
        const Label = renderLabel();
        if (labelAlign === "top") {
          return [LeftIcon, Label].filter(Boolean);
        }
        return Label || [];
      };
      return _createVNode(Cell, {
        "size": props.size,
        "class": bem({
          error: showError.value,
          disabled,
          [`label-${labelAlign}`]: labelAlign
        }),
        "center": props.center,
        "border": props.border,
        "isLink": props.isLink,
        "clickable": props.clickable,
        "titleStyle": labelStyle.value,
        "valueClass": bem("value"),
        "titleClass": [bem("label", [labelAlign, {
          required: showRequiredMark.value
        }]), props.labelClass],
        "arrowDirection": props.arrowDirection
      }, {
        // 此处为使用特定插槽
        icon: LeftIcon && labelAlign !== "top" ? () => LeftIcon : null,
        title: renderTitle,
        value: renderFieldBody,
        extra: slots.extra
      });
    };
  }
});
export {
  stdin_default as default,
  fieldProps,
  fieldSharedProps
};
